package com.leetcode.questiononehundardandfifty.栈;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Stack;

/**
 * @author wtcode
 * @Description
 * @date 2025/4/3 - 8:36
 */
public class Answer {

    public static void main(String[] args) {
        String s = "/.../a/../b/c/../d/./";
        //isValid(s);

        simplifyPath(s);

    }

    // 有效的括号
    public static boolean isValid(String s) {
        int length = s.length();

        if(length % 2 != 0){
            return false;
        }

        Map<Character, Character> pairs = new HashMap<Character, Character>() {{
            put(')', '(');
            put(']', '[');
            put('}', '{');
        }};
        Stack<Character> stack = new Stack<Character>();

        for (int i = 0; i < s.length(); i++) {
            if(pairs.containsKey(s.charAt(i))){
                if (stack.isEmpty() || stack.pop() != pairs.get(s.charAt(i))) {
                    return false;
                }
            }else {
                stack.push(s.charAt(i));
            }
        }

        return true;

    }


    // 简化路径
    public static String simplifyPath(String path) {
        String[] chars = path.split("/");
        LinkedList<String> stack = new LinkedList();
        for (String aChar : chars) {
            if("..".equals(aChar)){
                if(!stack.isEmpty()){
                    stack.removeLast();
                }
            }else if(aChar.length() > 0 && !".".equals(aChar)){
                stack.add(aChar);
            }
        }

        StringBuffer ans = new StringBuffer();
        if (stack.isEmpty()) {
            ans.append('/');
        } else {
            while (!stack.isEmpty()) {
                ans.append('/');
                ans.append(stack.removeFirst());
            }
        }
        return ans.toString();
    }

}
